el-tag<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="listQuery.keyword" placeholder="商品名称 | 标签" style="width: 200px;" class="filter-item" @keyup.enter.native="searchList" />
      <el-cascader
        v-model="categorygid"
        :options="categorygidOptions"
        :props="{ expandTrigger: 'hover', checkStrictly: true}"
        placeholder="商品类别"
        clearable
        filterable
        :show-all-levels="false"
        style="width: 200px;"
        class="filter-item"
      />
      <el-select v-model="listQuery.suppliergid" filterable placeholder="选择供货商" style="width: 200px;" class="filter-item" clearable>
        <el-option
          v-for="item in suppliergidOptions"
          :key="item.gid"
          :label="item.name"
          :value="item.gid"
        />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="searchList">
        搜索
      </el-button>
      <el-button class="filter-item" type="success" icon="el-icon-edit" @click="handleAdd">
        新增商品
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      :span-method="objectSpanMethod"
      style="width: 100%; margin-bottom:20px;"
    >
      <el-table-column label="名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="缩略图">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.faceImg&&scope.row.faceImg!==''"
            style="width: 60px;"
            :src="scope.row.faceImg"
            :preview-src-list="[scope.row.faceImg]"
          >
            <div slot="placeholder" class="image-slot" style="width:60px;height:30px;text-align:center;line-height:30px;">
              <i class="dot el-icon-loading" style="font-size:20px;" />
            </div>
          </el-image>
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="类别" align="center">
        <template slot-scope="{row}">
          <span>{{ row.categoryName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center">
        <template slot-scope="{row}">
          <el-tag v-for="(item) in getDouHao(row.tags||'',[])" :key="item" type="primary" style="margin:0 5px;">{{ item }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="供货商" align="center">
        <template slot-scope="{row}">
          <span>{{ row.supplierName|| '暂无' }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="链接" width="150px">
        <template slot-scope="scope">
          <el-button v-clipboard:copy="`/pages/product/product?id=${scope.row.gid}`" v-clipboard:success="clipboardSuccess" size="mini">拷贝地址</el-button>
        </template>
      </el-table-column>

      <!-- 规格开始 -->
      <el-table-column label="规格参数" align="center">
        <el-table-column label="规格" align="center" width="100px">
          <template slot-scope="scope">
            <span>{{ scope.row.warename }}</span>
          </template>
        </el-table-column>

        <el-table-column label="现价" align="center" width="100px">
          <template slot-scope="scope">
            <span>¥{{ scope.row.wareprice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="原价" align="center" width="100px">
          <template slot-scope="scope">
            <span>¥{{ scope.row.warereferencePrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="库存" align="center" width="100px">
          <template slot-scope="scope">
            <span>{{ scope.row.warestock }}</span>
          </template>
        </el-table-column>
        <el-table-column label="已售" align="center" width="100px">
          <template slot-scope="scope">
            <span>{{ scope.row.waresold }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160px">
          <template slot-scope="scope">
            <el-button-group>
              <el-button v-if="scope.row.warestate==0" type="info" icon="el-icon-download" size="mini" @click="setWareModelState(scope.row,-1)">
                下架
              </el-button>
              <el-button v-if="scope.row.warestate==-1" type="success" icon="el-icon-upload2" size="mini" @click="setWareModelState(scope.row,0)">
                上架
              </el-button>
              <el-button type="primary" plain size="mini" @click="changeStockOne(scope.row)">
                改库存
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>

      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220px">
        <template slot-scope="{row}">
          <el-button-group>
            <el-button v-if="row.state==0" type="info" icon="el-icon-download" size="mini" @click="setWareState(row,-1)">
              下架
            </el-button>
            <el-button v-if="row.state==-1" type="success" icon="el-icon-upload2" size="mini" @click="setWareState(row,0)">
              上架
            </el-button>
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="edit(row)">
              修改
            </el-button>
            <el-button v-if="row.status!='deleted'" size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :limit.sync="listQuery.pagesize"
      :page.sync="listQuery.page"
      @pagination="getList"
    />

    <el-dialog title="修改库存" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="18%">
      <el-form @keyup.enter.native="changeStock">
        <el-form-item>
          <el-button size="mini" :type="temp.type === 1?'primary':''" @click="temp.type = 1">
            增加
          </el-button>
          <el-button :type="temp.type === 2?'primary':''" size="mini" @click="temp.type = 2">
            减少
          </el-button>
        </el-form-item>
        <el-form-item :error="error" :label="temp.type ===2?'减少库存':'增加库存'" :rules="{type:'number',message:'请输入数字',required:true,trigger:'[blur,change]'}">
          <el-input v-model="temp.number" type="number" />
        </el-form-item>
        <el-form-item>
          <el-button type="success" size="mini" @click="changeStock()">
            确认
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import { getWares, delWare, updateStock, setWareState, setWareModelState } from '@/api/goods'
import { getSupplier } from '@/api/supplier'
import { getCategory } from '@/api/catetory'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import clipboard from '@/directive/clipboard/index.js'
import { renderTime, getDouHao, getCascader, deepClone } from '@/utils/util'

export default {
  name: 'Orders',
  components: { Pagination },
  directives: { waves, clipboard },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        keyword: '',
        categorygid: '', // 分类gid
        suppliergid: '', // 供货商gid
        page: 1, // 当前页
        pageSize: 10// 每页数量
      },
      categorygid: [],
      suppliergidOptions: [],
      categorygidOptions: [],
      dialogFormVisible: false,
      temp: {
        number: 0,
        gid: '',
        type: 1
      },
      status: 1 // 1加法  2减法
    }
  },
  computed: {
    error() {
      if (this.temp.number < 0) {
        return '库存不能小于0'
      }
      return ''
    }
  },
  watch: {
    'temp.number'(newValue) {
      if (newValue < 0) {
        this.temp.number = 0
      }
    },
    categorygid: {
      handler(value) {
        if (value instanceof Array) {
          this.listQuery.categorygid = value[value.length - 1]
        }
      },
      deep: true
    }
  },
  created() {
    this.getList()
    this.getCategory()
    this.getSupplier()
  },
  methods: {
    renderTime,
    getDouHao,
    getCascader,
    // 获取供货商
    getCategory() {
      getCategory().then(res => {
        if (res.result.length > 0) {
          // 将分类递归处理
          this.categorygidOptions = this.getCascader(res.result)
          console.log('递归处理之后的数据', this.categorygidOptions)
        }
      })
    },
    // 获取供货商
    getSupplier() {
      getSupplier().then(res => {
        this.suppliergidOptions = res.result.list
      })
    },
    // 1：域名 2：邮箱 3：网站4：安全
    clipboardSuccess() {
      this.$message({
        message: '复制成功',
        type: 'success',
        duration: 1500
      })
    },
    getList() {
      this.listLoading = true
      getWares(this.listQuery).then(res => {
        const waremodels = []
        this.total = res.result.total
        res.result.list.forEach((item) => {
          if (item.waremodels.length === 0) {
            waremodels.push(deepClone(Object.assign(item, { wareprice: '', warename: '暂无规格', waregid: '', modelCount: -1 })))
          }
          item.waremodels.forEach((waremodel, index) => {
            waremodels.push(deepClone(Object.assign(item, {
              modelCount: index === 0 ? item.waremodels.length : 0,
              waregid: waremodel.gid,
              warename: waremodel.name,
              wareprice: waremodel.price,
              warereferencePrice: waremodel.referencePrice,
              waresold: waremodel.sold,
              warestock: waremodel.stock,
              warestate: waremodel.state
            })))
          })
        })
        this.list = waremodels
        console.log('修改之后的list', this.list)
        this.listLoading = false
      })
    },
    searchList() {
      this.listQuery.page = 1
      this.getList()
    },
    edit(row) {
      this.$router.push('/goods/edit?gid=' + row.gid)
    },
    handleAdd() {
      this.$router.push('/goods/create')
    },
    handleDelete(row) {
      this.$confirm(`是否确认要删除${row.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delWare({ gid: row.gid }).then(res => {
          this.$notify({
            message: '删除成功！',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {})
    },
    setWareState(row, state) {
      this.$confirm(`是否确认要${state === -1 ? '下架' : '上架'}${row.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setWareState({ gid: row.gid, state }).then(res => {
          this.$notify({
            message: res.message,
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {})
    },
    setWareModelState(row, state) {
      this.$confirm(`是否确认要${state === -1 ? '下架' : '上架'}${row.name} ${row.warename}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setWareModelState({ gid: row.waregid, state }).then(res => {
          this.$notify({
            message: res.message,
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {})
    },
    // 打开dialog 操作
    changeStockOne(row) {
      this.dialogFormVisible = true
      this.temp.gid = row.waregid
      this.temp.number = 0
      this.temp.type = 1
    },
    changeStock() {
      updateStock(this.temp).then(res => {
        this.$message({
          message: '库存已经更改',
          type: 'success',
          duration: 2000
        })
        this.dialogFormVisible = false
        this.getList()
      })
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if ((columnIndex < 6 || columnIndex > 11) && row.modelCount !== 0) {
        return {
          rowspan: row.modelCount === -1 ? 1 : row.modelCount,
          colspan: 1
        }
      } else if (columnIndex < 6 || columnIndex > 11) {
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    }
  }
}
</script>
<style lang="scss">
    @import '@/assets/scss/mixin.scss';
    .el-form-item--medium{
      .el-form-item__content{
        display: flex;
        align-items: center;
        .el-input{
          &+.el-button{
            margin-left: 0.625rem;
          }
        }
        .el-button{
          &:not(:first-child){
            margin-left: 0.625rem;
          }
        }
      }
    }

</style>
